<template>
	<view class="container">
		<!-- 时间倒计时 -->
		<view>
			<span>剩余时间: {{ formattedTime }}</span>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				deadline: new Date("2024-06-08 09:20:44").getTime(),
				formattedTime: "",
				intervalId: null,//用来表示定时器的唯一标识符的变量
			}
		},
		created() {
			this.updateCountdown();
			this.intervalId = setInterval(() => {
				this.updateCountdown();
			}, 1000);
		},
		/**
		 * 退出界面销毁定时器的调用
		 */
		beforeDestroy() {
			clearInterval(this.intervalId);
		},
		methods: {
			updateCountdown() {
				//当前时间
				const now = new Date().getTime();
				//截至时间到现在的剩余时间
				const remainingTime = this.deadline - now;
				//如果剩余时间大于0，表明还没有到达，计算还剩多少天/小时/分钟/秒
				if (remainingTime > 0) {
					const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
					const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
					const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
					const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
					this.formattedTime = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
				} else {
					this.formattedTime = "已过期";
				}
			},
		}
	}
</script>

<style scoped>
	@import url('./timeCountdown.css');
</style>